package com.betterwood.dragon.service;

import com.alibaba.fastjson.JSON;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicInteger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Created By Chris Wang on 2019/6/27.
 */
@Slf4j
@Service
public class JedisService {

    @Resource(name = "stringRedisTemplate")
    private RedisTemplate<String, String> redisTemplate;

    public void set(final String key, final String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public void set(final String key, final String value, final long second) {
        redisTemplate.opsForValue().set(key, value);
        redisTemplate.expire(key, second, TimeUnit.SECONDS);
    }

    public void set(String prefix, Object key, Object value, long expire) {
        try {
            log.info("set redisKey : {},expire : {} ", key, expire);
            String redisKey = prefix + String.valueOf(key);
            String data = JSON.toJSONString(value);
            redisTemplate.opsForValue().set(redisKey, data);
            redisTemplate.expire(redisKey, expire, TimeUnit.HOURS);
        } catch (Exception e) {
        }
    }

    public Long getExpireTime(final String key, TimeUnit unit) {
        return redisTemplate.getExpire(key, unit);
    }

    public String get(final String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public <T> T get(String prefix, Object key, Class<T> clazz) {
        try {
            String redisKey = String.valueOf(key);
            // log.info("get redisKey : {}", key);
            String data = redisTemplate.opsForValue().get(prefix + redisKey);
            return JSON.parseObject(data, clazz);
        } catch (Exception e) {
        }
        return null;
    }

    public List<String> getList(final String key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    public void setList(final String key, final List list) {
        redisTemplate.opsForList().leftPushAll(key, list);
    }

    public void del(final String key) {
        redisTemplate.delete(key);
    }

    public void del(final Collection<String> keys) {
        redisTemplate.delete(keys);
    }

    public Set<String> like(final String prefix) {
        Set<String> keys = redisTemplate.keys(prefix + "*");
        return keys;
    }

    public boolean hasKey(final String key) {
        return redisTemplate.hasKey(key);
    }

    public int intIncrAndGet(String key) {
        RedisAtomicInteger counter = new RedisAtomicInteger(key, redisTemplate.getConnectionFactory());
        return counter.incrementAndGet();
    }
}
